<script setup>
import { ref, onMounted } from 'vue';
import { getMyCollectedArticles, uncollectCommunityArticle } from '@/api/community';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();
const articleList = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const loading = ref(false);

const loadMyCollectedArticles = async () => {
  loading.value = true;
  try {
    const res = await getMyCollectedArticles({ page: page.value, pageSize: pageSize.value });
    if ((res.code === 0 || res.code === 200) && res.data) {
      console.log('收藏文章API返回数据:', res.data);
      if (res.data.records && res.data.records.length > 0) {
        console.log('第一篇文章详情:', res.data.records[0]);
        
        // 标记所有文章使用备用显示方式
        res.data.records.forEach(article => {
          article.imageLoadFailed = true;
        });
        
        // 检查所有可能的字段
        const article = res.data.records[0];
        console.log('第一篇文章所有属性:');
        Object.keys(article).forEach(key => {
          console.log(`${key}: ${article[key]}`);
        });
      }
      articleList.value = res.data.records || [];
      total.value = res.data.total || 0;
    } else {
      ElMessage.error(res.message || '获取收藏文章失败');
    }
  } finally {
    loading.value = false;
  }
};

const handlePageChange = (val) => {
  page.value = val;
  loadMyCollectedArticles();
};
const handleSizeChange = (val) => {
  pageSize.value = val;
  page.value = 1;
  loadMyCollectedArticles();
};

const viewArticleDetail = (id) => {
  router.push(`/community/article/${id}`);
};

const handleUncollect = async (articleId) => {
  try {
    const res = await uncollectCommunityArticle(articleId)
    if ((res.code === 0 || res.code === 200) && res.data) {
      ElMessage.success('已取消收藏')
      loadMyCollectedArticles()
    } else {
      ElMessage.error(res.message || '取消收藏失败')
    }
  } catch (e) {
    ElMessage.error('取消收藏失败')
  }
}

const getImageUrl = (article) => {
  // 不要直接使用相对路径，因为会导致401错误
  // 我们应该从article对象取出正确的完整URL或从文章内容中提取
  
  // 作为紧急解决方案，直接返回文章页面首字母替代图片
  article.imageLoadFailed = true;
  return '';
};

const handleImageError = (event, article) => {
  console.error('图片加载失败:', event.target.src);
  
  // 获取当前失败的URL
  const failedUrl = event.target.src;
  
  // 尝试备用策略: 
  // 1. 如果当前URL已经是默认图片，不再尝试
  if (failedUrl.includes('default-cover.png')) {
    // 设置标志，使用替代显示
    article.imageLoadFailed = true;
    return;
  }
  
  // 2. 尝试构造一个通用的文章封面API路径
  const baseUrl = import.meta.env.VITE_API_BASE_URL || '';
  if (article && article.id) {
    // 防止循环错误
    event.target.onerror = null;
    
    // 尝试另一种API路径格式
    const altImageUrl = `${baseUrl}/community/images/${article.id}`;
    console.log('尝试备用图片URL:', altImageUrl);
    event.target.src = altImageUrl;
    return;
  }
  
  // 3. 最后使用默认图片
  event.target.src = '/images/default-cover.png';
  event.target.onerror = () => {
    article.imageLoadFailed = true;
  };
};

onMounted(() => {
  loadMyCollectedArticles();
});
</script>

<template>
  <div class="collect-container">
    <div class="content-container">
      <div class="page-header">
        <h1 class="page-title">我的收藏</h1>
        <p class="page-description">收藏的文章列表</p>
      </div>
      <div class="article-list">
        <div v-for="article in articleList" :key="article.id" class="article-card" @click="viewArticleDetail(article.id)">
          <div class="article-cover">
            <img 
              :src="getImageUrl(article)" 
              alt="Article Cover"
              @error="handleImageError($event, article)"
            >
            
            <div v-if="article.imageLoadFailed" class="fallback-cover">
              <span>{{ article.title.charAt(0) }}</span>
            </div>
          </div>
          <div class="article-content">
            <h2 class="article-title">{{ article.title }}</h2>
            <p class="article-summary">{{ article.summary }}</p>
            <div class="article-meta">
              <div class="article-author">
                <img :src="article.creatorAvatar || article.authorAvatar || '/images/default-avatar.png'" alt="Author Avatar" class="author-avatar">
                <span class="author-name">{{ article.createUser || article.authorName || '未知用户' }}</span>
              </div>
              <span class="article-date">{{ article.createTime || article.date }}</span>
            </div>
          </div>
        </div>
      </div>
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :current-page="page"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; display: flex; justify-content: flex-end;"
      />
    </div>
  </div>
</template>

<style scoped>
.collect-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4ebf5 100%);
  font-family: 'Inter', 'Source Sans Pro', 'Microsoft YaHei', sans-serif;
  padding-bottom: 50px;
}

.content-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #2c5dff;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.page-title::before {
  content: "";
  display: inline-block;
  width: 5px;
  height: 28px;
  background: linear-gradient(180deg, #2c5dff 0%, #0097ff 100%);
  border-radius: 3px;
  margin-right: 15px;
}

.page-description {
  color: #6b7280;
  font-size: 16px;
}

.article-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
  gap: 25px;
}

.article-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.07);
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
  border: 1px solid rgba(229, 231, 235, 0.7);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.article-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(44, 93, 255, 0.15);
  border-color: rgba(44, 93, 255, 0.3);
}

.article-cover {
  height: 180px;
  overflow: hidden;
  position: relative;
}

.article-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.article-card:hover .article-cover img {
  transform: scale(1.05);
}

.article-content {
  padding: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.article-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.3;
  min-height: 48px;
}

.article-summary {
  color: #6b7280;
  margin-bottom: 15px;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  line-height: 1.5;
  flex-grow: 1;
}

.article-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
  font-size: 14px;
  color: #94a3b8;
}

.article-author {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
}

.author-name {
  color: #2c5dff;
  font-weight: 500;
}

.article-date {
  font-size: 13px;
  color: #94a3b8;
}

.article-tag {
  position: absolute;
  top: 12px;
  right: 12px;
  background: linear-gradient(135deg, #2c5dff 0%, #0097ff 100%);
  color: white;
  padding: 5px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  box-shadow: 0 5px 15px rgba(44, 93, 255, 0.2);
}

.empty-state {
  text-align: center;
  padding: 60px 0;
  color: #94a3b8;
}

.empty-icon {
  font-size: 60px;
  color: #e5e7eb;
  margin-bottom: 20px;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: #6b7280;
  margin-bottom: 10px;
}

.empty-description {
  font-size: 15px;
  color: #94a3b8;
  margin-bottom: 20px;
}

.empty-button {
  background: linear-gradient(135deg, #2c5dff 0%, #0097ff 100%);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  cursor: pointer;
  box-shadow: 0 5px 15px rgba(44, 93, 255, 0.2);
  transition: all 0.2s;
}

.empty-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(44, 93, 255, 0.3);
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #2c5dff;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled):hover) {
  color: #2c5dff;
}

.fallback-cover {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #2c5dff 0%, #0097ff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.fallback-cover span {
  font-size: 64px;
  font-weight: bold;
  color: white;
  opacity: 0.7;
  text-transform: uppercase;
}
</style> 